<script setup lang="ts">
import {
  addUserAddress,
  deleteUserAddress,
  getUserAddress,
  getUserAddressList,
  setUserAddressDefault,
  upUserAddress,
} from "@/api/address/address";
import { getLocation } from "@/utils/positioningUtils";
import type { FormInstance } from "element-plus";
import { reactive, ref, toRef, toRefs } from "vue";
import {
  provinceAndCityData,
  pcTextArr,
  regionData,
  pcaTextArr,
  codeToText,
} from "element-china-area-data";
import router from "@/router";
interface Address {
  userAddressId: number;
  userId: number;
  receiverName: string;
  receiverPhone: string;
  country: string;
  province: string;
  city: string;
  district: string;
  street: string;
  postalCode: string;
  isDefault: number;
  createTime: string;
  updateTime: string;
  tag: string;
  region: string[];
}
const tableData = ref();
const dialogVisible = ref(false);
const formEl = ref();
const title = ref();
const isSumbit = ref(false);
const loading = ref(false);
//表单校验
const receiverNameValidator = (rule: any, value: any, callback: any) => {
  if (!value || value.trim() === "") {
    callback(new Error("收货人不能为空"));
  } else if (value.trim().length < 1 || value.trim().length > 10) {
    callback(new Error("长度为1到10位"));
  } else {
    callback();
  }
};
const receiverPhoneValidator = (rule: any, value: any, callback: any) => {
  if (!value || value.trim() === "") {
    callback(new Error("手机号不能为空"));
  } else if (value.trim().length != 11) {
    callback(new Error("长度为11位"));
  } else {
    callback();
  }
};
const streetValidator = (rule: any, value: any, callback: any) => {
  if (!value || value.trim() === "") {
    callback(new Error("详细不能为空"));
  } else if (value.trim().length < 1 || value.trim().length > 20) {
    callback(new Error("长度为1到20位"));
  } else {
    callback();
  }
};
const data = reactive({
  form: <Address>{
    isDefault: 0,
    region: ["", "", ""],
  },
  rules: {
    receiverName: [
      {
        required: true,
        validator: receiverNameValidator,
        trigger: "blur",
      },
    ],
    receiverPhone: [
      {
        required: true,
        validator: receiverPhoneValidator,
        trigger: "blur",
      },
    ],
    street: [
      {
        required: true,
        validator: streetValidator,
        trigger: "blur",
      },
    ],
    region: [
      {
        required: true,
        message: "请选择所在地区",
        trigger: "change",
      },
    ],
  },
});
const { form, rules } = toRefs(data);
//初始化
async function loadUseraddressList() {
  loading.value = true;
  await getUserAddressList().then((response) => {
    tableData.value = response.data.rows;
    console.log(tableData.value);
  });
  loading.value = false;
}

// 新建地址按钮
const AddUserAddressButton = () => {
  title.value = "新增收货地址";
  dialogVisible.value = true;
  isSumbit.value = true;
};
//设置默认按钮
const setDefault = async (item: Address) => {
  item.isDefault = 1;
  await setUserAddressDefault(item);
  loadUseraddressList();
};
//修改按钮
const EditSumbit = (item: Address) => {
  title.value = "修改收货地址";
  dialogVisible.value = true;
  isSumbit.value = false;
  getUserAddress(item.userAddressId).then((response) => {
    form.value = response.data.data;
    form.value.region = [form.value.province, form.value.city, form.value.district];
    console.log(form.value.region);
  });
};
//删除按钮
const handleDelete = async (item: Address) => {
  await deleteUserAddress(item.userAddressId);
  loadUseraddressList();
};
//提交按钮
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (isSumbit.value) {
        form.value.province = form.value.region[0];
        form.value.city = form.value.region[1];
        form.value.district = form.value.region[2];
        await addUserAddress(form.value);
      } else {
        await upUserAddress(form.value);
      }
      dialogVisible.value = false;
      loadUseraddressList();
    }
  });
};

//表单重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
function getIpAddress() {
  getLocation().then((response) => {
    form.value.region = [
      response.address_detail.province,
      response.address_detail.city,
      response.address_detail.district,
    ];
  });
}

loadUseraddressList();
</script>

<template>
  <el-space direction="vertical">
    <div style="width: 1000px; text-align: center">
      <el-button type="primary" @click="AddUserAddressButton">新建地址</el-button>
      <el-divider />
    </div>
    <el-card
      v-if="tableData !== undefined && tableData.length > 0"
      v-for="item in tableData"
      style="width: 1000px"
      shadow="never"
      v-loading="loading"
    >
      <div style="font-size: 20px" v-if="item.tag !== null">{{ item.tag }}</div>
      <div style="font-size: 20px" v-else>
        <span>{{ item.receiverName }}</span> <span>{{ item.province }}</span>
      </div>
      <div>收货人:{{ item.receiverName }}</div>
      <div>
        所在地区:<span>{{ item.province }}</span
        ><span>{{ item.city }}</span
        ><span>{{ item.district }}</span>
      </div>
      <div>地址:{{ item.street }}</div>
      <div>手机号:{{ item.receiverPhone }}</div>
      <div style="float: right">
        <el-button
          link
          type="primary"
          @click="setDefault(item)"
          v-if="item.isDefault === 0"
          >设置默认</el-button
        >
        <el-button link type="primary" icon="Edit" @click="EditSumbit(item)">
          修改
        </el-button>
        <el-popconfirm title="确定要删除吗？" @confirm="handleDelete(item)">
          <template #reference>
            <el-button link type="primary" icon="Delete">删除</el-button>
          </template>
        </el-popconfirm>
      </div>
    </el-card>
    <el-empty v-else description="您还没有创建地址哦~">
      <el-button @click="AddUserAddressButton" type="primary">去新建</el-button>
    </el-empty>
  </el-space>

  <!-- 新增修改 -->
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="800"
    @close="resetForm(formEl)"
  >
    <el-form
      ref="formEl"
      style="max-width: 600px"
      :model="form"
      :rules="rules"
      label-width="auto"
      status-icon
      label-position="top"
    >
      <el-form-item prop="receiverName" label="收货人:">
        <el-input v-model="form.receiverName" style="width: 240px"></el-input>
      </el-form-item>
      <el-form-item prop="region" label="所在地区:">
        <el-cascader
          :options="pcaTextArr"
          v-model="form.region"
          placeholder="选择省市区"
        ></el-cascader>
        <el-button
          @click="getIpAddress()"
          type="info"
          icon="Position"
          circle
          style="margin-left: 10px"
        />
      </el-form-item>
      <el-form-item prop="street" label="详细地址:">
        <el-input v-model="form.street" style="width: 500px"></el-input>
      </el-form-item>
      <el-form-item prop="receiverPhone" label="手机号:">
        <el-input v-model="form.receiverPhone" style="width: 240px"></el-input>
      </el-form-item>
      <el-form-item label="地址别名:">
        <el-input v-model="form.tag" style="width: 240px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="submitForm(formEl)">保存收货地址</el-button>
      </el-form-item>
    </el-form></el-dialog
  >
</template>
<style></style>
